<template>
  <div class="board-detail-page">
    <!-- 加载状态 -->
    <div v-if="!isLoad" class="loading-container">
      <van-loading class="loading">加载中...</van-loading>
    </div>
    
    <!-- 帖子不存在 -->
    <div v-if="isLoad === null" class="not-exist">
      <van-empty description="帖子不存在或已被删除" />
    </div>

    <!-- 主要内容 -->
    <div v-if="isLoad === true" class="main">
      <!-- 帖子详情 -->
      <div class="article card shadow-project">
        <!-- 时间和分类信息 -->
        <div class="time">
          <span>
            <van-icon name="clock-o" />
            {{ formatTime(postDetail.createTimestamp) }}
          </span>
          <span>表白墙</span>
          <span>
            <van-icon name="eye-o" />
            {{ postDetail.visitNum || 0 }}
          </span>
        </div>

        <!-- 帖子内容列表 -->
        <div class="list">
          <!-- 表白对象 -->
          <div class="item">
            <div class="left">表白对象</div>
            <div class="right">{{ postDetail.title || '匿名表白' }}</div>
          </div>

          <!-- 表白内容 -->
          <div class="item">
            <div class="left">表白内容</div>
            <div class="right">{{ postDetail.content || '暂无内容' }}</div>
          </div>

          <!-- 图片展示 -->
          <div v-if="hasImages(postDetail)" class="item">
            <div class="left">图片</div>
            <div class="right pics">
              <img 
                v-if="postDetail.pic1"
                :src="postDetail.pic1"
                class="loading"
                @click="previewImage(postDetail.pic1, getImageList(postDetail))"
                alt="表白图片"
              />
              <img 
                v-if="postDetail.pic2"
                :src="postDetail.pic2"
                class="loading"
                @click="previewImage(postDetail.pic2, getImageList(postDetail))"
                alt="表白图片"
              />
              <img 
                v-if="postDetail.pic3"
                :src="postDetail.pic3"
                class="loading"
                @click="previewImage(postDetail.pic3, getImageList(postDetail))"
                alt="表白图片"
              />
            </div>
          </div>

          <!-- 发布者 -->
          <div v-if="postDetail.nickName" class="item">
            <div class="left">发布者</div>
            <div class="right">{{ postDetail.nickName }}</div>
          </div>
        </div>
      </div>

      <!-- 评论区域 -->
      <div class="comment-section">
        <div class="comment-header">
          <h3>评论 ({{ totalComments }})</h3>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div 
            v-for="comment in commentList" 
            :key="comment.commentId"
            class="comment-item"
          >
            <!-- 主评论 -->
            <div class="comment-main">
              <div class="comment-avatar">
                <img 
                  :src="getCommentAvatar(comment.image)" 
                  alt="头像" 
                  @error="handleImageError"
                />
              </div>
              <div class="comment-content">
                <div class="comment-user">{{ comment.nickName || '匿名用户' }}</div>
                <div class="comment-text">{{ comment.content }}</div>
                <div class="comment-actions">
                  <span class="comment-time">{{ comment.createTime }}</span>
                  <div class="comment-ops">
                    <span @click="toggleCommentLike(comment)" class="like-btn">
                      <van-icon :name="comment.liked ? 'good-job' : 'good-job-o'" />
                      {{ comment.likeNum || 0 }}
                    </span>
                    <span @click="showReplyInput(comment)" class="reply-btn">
                      <van-icon name="chat-o" />
                      回复
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 子评论 -->
            <div v-if="comment.subComments && comment.subComments.length > 0" class="sub-comments">
              <div 
                v-for="subComment in comment.subComments" 
                :key="subComment.commentId"
                class="sub-comment-item"
              >
                <div class="sub-comment-avatar">
                  <img 
                    :src="getCommentAvatar(subComment.image)" 
                    alt="头像" 
                    @error="handleImageError"
                  />
                </div>
                <div class="sub-comment-content">
                  <div class="sub-comment-user">
                    {{ subComment.nickName || '匿名用户' }}
                    <span v-if="subComment.lastNick !== undefined" class="reply-to">
                      回复 {{ subComment.lastNick || 'null' }}
                    </span>
                  </div>
                  <div class="sub-comment-text">{{ subComment.content }}</div>
                  <div class="sub-comment-actions">
                    <span class="sub-comment-time">{{ subComment.createTime }}</span>
                    <div class="sub-comment-ops">
                      <span @click="showSubReplyInput(comment, subComment)" class="reply-btn">
                        <van-icon name="chat-o" />
                        回复
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 查看更多子评论 -->
              <div 
                v-if="comment.subCount > comment.subComments.length" 
                class="load-more-sub"
                @click="loadMoreSubComments(comment)"
              >
                查看更多回复 ({{ comment.subCount - comment.subComments.length }})
              </div>
            </div>

            <!-- 回复输入框 -->
            <div v-if="replyingComment?.commentId === comment.commentId && replyingComment?.type === 'main'" class="reply-input-section">
              <van-field
                v-model="replyContent"
                type="textarea"
                placeholder="写下你的回复..."
                rows="3"
                autosize
              />
              <div class="reply-actions">
                <van-button size="small" @click="cancelReply">取消</van-button>
                <van-button type="primary" size="small" @click="submitReply">发送</van-button>
              </div>
            </div>

            <!-- 子评论回复输入框 -->
            <div v-if="replyingComment?.parentCommentId === comment.commentId && replyingComment?.type === 'sub'" class="sub-reply-input-section">
              <van-field
                v-model="replyContent"
                type="textarea"
                :placeholder="`回复 ${replyingComment?.targetNickName}...`"
                rows="3"
                autosize
              />
              <div class="reply-actions">
                <van-button size="small" @click="cancelReply">取消</van-button>
                <van-button type="primary" size="small" @click="submitSubReply">发送</van-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多评论 -->
        <div v-if="hasMoreComments" class="load-more-comments">
          <van-button 
            :loading="loadingComments" 
            @click="loadMoreComments"
            block
            plain
          >
            加载更多评论
          </van-button>
        </div>
      </div>
    </div>

    <!-- 底部评论输入 -->
    <div class="comment-input-bar">
      <van-field
        v-model="newComment"
        placeholder="写下你的评论..."
        class="comment-input"
      />
      <van-button 
        type="primary" 
        size="small"
        @click="submitComment"
        :disabled="!newComment.trim()"
      >
        发送
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { boardApi } from '@/api/board'
import { commentApi } from '@/api/comment'
import { showToast, showImagePreview } from 'vant'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

// 设置页面标题
appStore.setTitle('表白详情')

// 响应式数据
const isLoad = ref<boolean | null>(false)
const postDetail = ref<any>({})
const commentList = ref<any[]>([])
const totalComments = ref(0)
const hasMoreComments = ref(true)
const loadingComments = ref(false)
const newComment = ref('')
const replyContent = ref('')
const replyingComment = ref<any>(null)

// 分页参数
const commentParams = reactive({
  pageNo: 0,  // 从0开始
  pageSize: 10,
  postId: '',
  lastEndKey: '',
  endCommentId: ''
})

// 获取帖子ID
const postId = route.params.id as string

// 加载帖子详情
const loadPostDetail = async () => {
  if (!postId) {
    isLoad.value = null
    return
  }

  try {
    // 调用访问接口增加浏览量
    await boardApi.visit(postId)
    
    // 获取帖子详情
    const response = await boardApi.getDetail(postId)
    
    if (response.code === 1 && response.data) {
      postDetail.value = response.data
      isLoad.value = true
      
      // 加载评论
      commentParams.postId = postId
      await loadComments(true)
    } else {
      isLoad.value = null
    }
  } catch (error: any) {
    console.error('加载帖子详情失败:', error)
    if (error.message?.includes('401') || error.message?.includes('未授权')) {
      showToast('请先登录后查看')
      router.push('/login')
    } else {
      isLoad.value = null
    }
  }
}

// 加载评论
const loadComments = async (refresh = false) => {
  try {
    loadingComments.value = true
    
    if (refresh) {
      commentParams.pageNo = 0  // 从0开始
      commentParams.lastEndKey = ''
      commentParams.endCommentId = ''
      commentList.value = []
    }

    const response = await commentApi.getByPost(commentParams)
    
    if (response.code === 1 && response.data) {
      const { list, total } = response.data
      
      if (refresh) {
        commentList.value = list || []
      } else {
        commentList.value.push(...(list || []))
      }
      
      totalComments.value = total || 0
      hasMoreComments.value = (list || []).length === commentParams.pageSize
      
      // 更新分页参数
      if (list && list.length > 0) {
        const lastComment = list[list.length - 1]
        commentParams.endCommentId = lastComment.commentId
        commentParams.pageNo++
      }
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    showToast('加载评论失败')
  } finally {
    loadingComments.value = false
  }
}

// 加载更多评论
const loadMoreComments = () => {
  if (!hasMoreComments.value || loadingComments.value) return
  loadComments(false)
}

// 加载更多子评论
const loadMoreSubComments = async (comment: any) => {
  try {
    const params = {
      pageNo: 0,  // 从0开始
      pageSize: 10,
      commentId: comment.commentId,
      postId: postId,
      endCommentId: comment.subComments[comment.subComments.length - 1]?.commentId || ''
    }

    const response = await commentApi.getMoreSubComments(params)
    
    if (response.code === 1 && response.data) {
      comment.subComments.push(...response.data)
    }
  } catch (error) {
    console.error('加载更多子评论失败:', error)
    showToast('加载失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) return

  try {
    // 发表一级评论
    const params = {
      postId: postId,
      content: newComment.value.trim(),
      lastId: '',  // 一级评论为空
      lastCommentId: ''  // 一级评论为空
    }

    const response = await commentApi.add(params)
    
    if (response.code === 1) {
      showToast('评论成功')
      newComment.value = ''
      // 重新加载评论
      await loadComments(true)
    } else {
      showToast(response.msg || '评论失败')
    }
  } catch (error) {
    console.error('评论失败:', error)
    showToast('评论失败')
  }
}

// 显示回复输入框（一级评论）
const showReplyInput = (comment: any) => {
  replyingComment.value = {
    ...comment,
    type: 'main'
  }
  replyContent.value = ''
}

// 显示子评论回复输入框
const showSubReplyInput = (parentComment: any, subComment: any) => {
  replyingComment.value = {
    commentId: subComment.commentId,
    userId: subComment.userId,
    nickName: subComment.nickName,
    parentCommentId: parentComment.commentId,
    targetNickName: subComment.nickName,
    type: 'sub'
  }
  replyContent.value = ''
}

// 取消回复
const cancelReply = () => {
  replyingComment.value = null
  replyContent.value = ''
}

// 提交回复（一级评论）
const submitReply = async () => {
  if (!replyContent.value.trim() || !replyingComment.value) return

  try {
    // 回复一级评论的逻辑：
    // lastId = 一级评论的commentId
    // lastCommentId = 一级评论的commentId
    const params = {
      postId: postId,
      content: replyContent.value.trim(),
      lastId: replyingComment.value.commentId,  // 一级评论的ID
      lastCommentId: replyingComment.value.commentId  // 直接回复的评论ID
    }

    const response = await commentApi.add(params)
    
    if (response.code === 1) {
      showToast('回复成功')
      cancelReply()
      // 重新加载评论
      await loadComments(true)
    } else {
      showToast(response.msg || '回复失败')
    }
  } catch (error) {
    console.error('回复失败:', error)
    showToast('回复失败')
  }
}

// 提交子评论回复
const submitSubReply = async () => {
  if (!replyContent.value.trim() || !replyingComment.value) return

  try {
    // 回复子评论的逻辑：
    // lastId = 一级评论的commentId（归属的顶级评论）
    // lastCommentId = 直接回复的子评论ID
    const params = {
      postId: postId,
      content: replyContent.value.trim(),
      lastId: replyingComment.value.parentCommentId,  // 一级评论的ID
      lastCommentId: replyingComment.value.commentId  // 直接回复的子评论ID
    }

    const response = await commentApi.add(params)
    
    if (response.code === 1) {
      showToast('回复成功')
      cancelReply()
      // 重新加载评论
      await loadComments(true)
    } else {
      showToast(response.msg || '回复失败')
    }
  } catch (error) {
    console.error('回复失败:', error)
    showToast('回复失败')
  }
}

// 点赞评论
const toggleCommentLike = async (comment: any) => {
  try {
    if (comment.liked) {
      await commentApi.dislike(comment.commentId)
      comment.liked = false
      comment.likeNum = Math.max(0, (comment.likeNum || 0) - 1)
    } else {
      await commentApi.like(comment.commentId)
      comment.liked = true
      comment.likeNum = (comment.likeNum || 0) + 1
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    showToast('操作失败')
  }
}

// 预览图片
const previewImage = (current: string, images: string[]) => {
  showImagePreview({
    images,
    startPosition: images.indexOf(current)
  })
}

// 检查是否有图片
const hasImages = (item: any) => {
  return item.pic1 || item.pic2 || item.pic3
}

// 获取图片列表
const getImageList = (item: any) => {
  const images = []
  if (item.pic1) images.push(item.pic1)
  if (item.pic2) images.push(item.pic2)
  if (item.pic3) images.push(item.pic3)
  return images
}

// 格式化时间
const formatTime = (timestamp: string | number) => {
  if (!timestamp) return ''
  const date = new Date(typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000)
  return date.toLocaleString()
}

// 获取评论头像
const getCommentAvatar = (imageUrl: string | null | undefined) => {
  // 如果没有图片或为null，返回默认头像
  if (!imageUrl || imageUrl === 'null') {
    return '/images/default-avatar.svg'
  }
  
  // 如果是完整的URL，直接返回
  if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
    return imageUrl
  }
  
  // 如果是相对路径，可能需要拼接基础URL
  return imageUrl
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/images/default-avatar.svg'
}

// 页面加载
onMounted(() => {
  loadPostDetail()
})
</script>

<style scoped>
.board-detail-page {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 80px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.not-exist {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.main {
  padding: 12px;
}

.article {
  background-color: #fff;
  padding: 20px 15px;
  border-radius: 10px;
  margin-bottom: 15px;
  position: relative;
  overflow: hidden;
}

.time {
  font-size: 12px;
  color: #bbb;
  margin-bottom: 15px;
}

.time > span {
  margin-right: 10px;
}

.list {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.list .item {
  width: 100%;
  display: flex;
  align-items: flex-start;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.list .item:last-child {
  border-bottom: 0;
}

.list .item .left {
  font-size: 14px;
  color: #999;
  width: 80px;
  flex-shrink: 0;
}

.list .item .right {
  flex: 1;
  font-size: 14px;
  color: #333;
  word-break: break-all;
}

.list .item .right.pics {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.list .item .right.pics img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

/* 评论区域 */
.comment-section {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
}

.comment-header h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
}

.comment-item {
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.comment-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.comment-main {
  display: flex;
  gap: 10px;
}

.comment-avatar img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 5px;
}

.comment-text {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 8px;
}

.comment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-ops {
  display: flex;
  gap: 15px;
}

.like-btn, .reply-btn {
  font-size: 12px;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 3px;
}

.like-btn:hover, .reply-btn:hover {
  color: #1989fa;
}

/* 子评论 */
.sub-comments {
  margin-top: 10px;
  margin-left: 46px;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 10px;
}

.sub-comment-item {
  display: flex;
  gap: 8px;
  margin-bottom: 10px;
}

.sub-comment-item:last-child {
  margin-bottom: 0;
}

.sub-comment-avatar img {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  object-fit: cover;
}

.sub-comment-content {
  flex: 1;
}

.sub-comment-user {
  font-size: 13px;
  color: #333;
  font-weight: 500;
  margin-bottom: 3px;
}

.reply-to {
  color: #1989fa;
  font-weight: normal;
}

.sub-comment-text {
  font-size: 13px;
  color: #666;
  line-height: 1.3;
  margin-bottom: 3px;
}

.sub-comment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 3px;
}

.sub-comment-time {
  font-size: 11px;
  color: #999;
}

.sub-comment-ops {
  display: flex;
  gap: 10px;
}

.sub-reply-input-section {
  margin-top: 10px;
  margin-left: 46px;
  background-color: #f0f8ff;
  border-radius: 8px;
  padding: 10px;
  border-left: 3px solid #1989fa;
}

.load-more-sub {
  text-align: center;
  color: #1989fa;
  font-size: 13px;
  cursor: pointer;
  padding: 8px;
  margin-top: 5px;
}

.load-more-sub:hover {
  background-color: #f0f0f0;
  border-radius: 4px;
}

/* 回复输入 */
.reply-input-section {
  margin-top: 10px;
  margin-left: 46px;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 10px;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.load-more-comments {
  margin-top: 20px;
}

/* 底部评论输入 */
.comment-input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 15px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
  align-items: center;
  z-index: 1000;
}

.comment-input {
  flex: 1;
}

/* 工具类 */
.card { background-color: #fff; }
.shadow-project { box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); }
</style>